﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Xml.Serialization;
using System.IO;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml;

namespace NETXPF.Library
{
    /// <summary>
    /// Provides utility functions for XML persistance, and for XSL transform.
    /// </summary>
    public static class XMLAdapter
    {
        public static XslCompiledTransform Transform(XmlReader xml, XmlReader xsl, XmlWriter output, XslCompiledTransform cachedTransform)
        {
            XPathDocument xmlDoc = new XPathDocument(xml);
            XslCompiledTransform xslt = new XslCompiledTransform();
            if (cachedTransform == null)
            {
                XPathDocument xslDoc = new XPathDocument(xsl);
                xslt.Load(xslDoc, XsltSettings.TrustedXslt, null);
            }
            else
            {
                xslt = cachedTransform;
            }
            xslt.Transform(xmlDoc, output);
            return xslt;
        }
        public static void ToXML(object o, string fileName)
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                ToXMLStream(o, fs);
            }
        }
        public static void ToXMLStream(object o, Stream stream)
        {
            XmlSerializer xs = new XmlSerializer(o.GetType());
            xs.Serialize(stream, o);
        }
        public static T FromXML<T>(string fileName)
        {
            T o;
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                o = FromXMLStream<T>(fs);
            }
            return o;
        }

        public static T FromXMLStream<T>(Stream stream)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            object o = xs.Deserialize(stream);
            return (T)o;
        }

        public static T FromXMLReader<T>(XmlReader reader)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            object o = xs.Deserialize(reader);
            return (T)o;
        }

        public static T FromXMLString<T>(string xmlCode)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(xmlCode);
            return (T)xs.Deserialize(sr);
        }
    }
}